<?php
namespace app\common\model;

use think\facade\Db;

trait TraitPay
{


    //获取订单支付信息
    public static function getOrderPayInfo(array $php_input=[])
    {
        $order_id = $php_input['order_id']??'';

        if(empty($order_id)) throw new \Exception('订单信息异常:order_id');
        //模型
        $model = self::where(['id'=>$order_id])->find();
        if(empty($model)) throw new \Exception('订单信息异常');
        //判断订单是否可以支付
        if(method_exists($model,'checkOrderPayState')){
            $model->checkOrderPayState();
        }

        return $model;
    }

    /**
     * @param array $php_input 其它数据
     * @throws
     * @return array
     */
    public static function usePayWay(array $php_input=[])
    {
        $order_id = $php_input['order_id']??'';
        $pay_way = $php_input['pay_way']??'2';
        $pay_platform = $php_input['platform']??'';

        if(empty($order_id)) throw new \Exception('订单信息异常:order_id');
        if(empty($pay_way)) throw new \Exception('订单支付方式异常:pay_way');

        //获取订单支付对象
        $model = self::getOrderPayInfo($php_input);

        !empty($php_input['openid']) && $model->setAttr('pay_way_open_id', $php_input['openid']);
        $pay_info=[
            'provider' => 'yue',
        ];
        $is_pay = 0;
        if($pay_way==1){
            $user_id = $php_input['uid']??0;
            if(empty($user_id)) throw new \Exception('请先登录');
            //余额付款
            $userModel = UserModel::find($user_id);
            if(empty($userModel)) throw new \Exception('请先登录2');
            $q_money = $userModel['money'];
            if ( $q_money < $model['pay_money'] )  throw new \Exception('钱包余额不足');
            try{
                Db::startTrans();
                //扣钱
                $row_num = UserModel::where(['id'=>$user_id,'money'=>$q_money])->update([
                    'money'=>Db::raw('money-'.$model['pay_money'])
                ]);
                if(empty($row_num)) throw new \Exception('操作频繁,请稍后尝试');
                //付款成功
                $model->_sure_pay($pay_way);


                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                throw new \Exception($e->getMessage());
            }
            $is_pay = 1;

        }elseif($pay_way==2){
            //微信
            $pay_info['provider'] = 'wxpay';
            if($pay_platform=='h5'){
                $url = \app\common\service\WechatV3Pay::h5($model);
                $pay_info['url'] = $url.'&redirect_url='.urlencode(url('order/index',[],false,true)->build());
            }elseif($pay_platform=='native'){
                $code_url =  \app\common\service\WechatV3Pay::native($model);//
                $pay_info['orderInfo'] = $code_url;
            }elseif($pay_platform=='app'){
                $openid = $php_input['openid']??'';
                if(empty($openid)) throw new \Exception('请先获取用户:openid');
                $sign_data = \app\common\service\WechatV3Pay::jsapi($model,$openid);//
                $pay_info = array_merge($pay_info,$sign_data);

            }else{
                $sign_data = \app\common\service\WechatV3Pay::app($model);
                $pay_info['orderInfo'] = $sign_data;
            }
        }elseif ($pay_way==3){
            //支付宝
            $pay_info['provider'] = 'alipay';
            if($pay_platform=='h5'){
                $sign_data = (new \app\common\service\Alipay())->wapPay($model);//
                $pay_info['orderInfo'] = $sign_data;
            }elseif($pay_platform=='native'){
                $sign_data = (new \app\common\service\Alipay())->webPay($model);//
                $pay_info['orderInfo'] = $sign_data;
            }else{
                $sign_data = (new \app\common\service\Alipay())->appPay($model);//
                $pay_info['orderInfo'] = $sign_data;

            }
        }

        return [
            'pay_way'=>$pay_way,
            'is_pay'=>$is_pay,
            'info'=> $pay_info,

        ];
    }



    /**
     * 支付凭据
     * @param $origin string   支付来源 微信 支付宝
     * @param $mode string   支付方式 微信 支付宝
     * */
    public function getPayInfo($origin,$mode)
    {
        $pay_money = $this->getAttr('pay_money');
        $order_no = $this->getAttr('no');
        $namespace_class = get_class($this);
        $namespace_class_arr = explode("\\",$namespace_class);
        $class_name =$namespace_class_arr[count($namespace_class_arr)-1];
//        dump($class_name,basename($namespace_class),$namespace_class);exit;
        return [
            'body' => '订单支付',
            'attach' => $origin.'&'.$class_name,
            'no' =>  $order_no,
            'pay_money' => $pay_money,
            'expire_time' => self::ORDER_EXP_TIME,
            'goods_tag' => 'goods',
            'notify_url' => url('pay/'.$mode.'Notify',[],false,true)->build(),
            'return_url' => url('order/index',['id'=>$this['id']],false,true)->build()
        ];
    }

    //付款方式
    public function _sure_pay($pay_way)
    {

    }


    //订单回调通知
    public static function handleNotify($order_no,array $data,$pay_way='',$pay_origin='')
    {
        $model = self::where(['no'=>$order_no])->find();
        if(empty($model)){
            return;
        }elseif(!empty($model['pay_time'])){ // 已支付
            return;
        }
        //保存第三方支付信息
        $model->setAttr('pay_way',$pay_way);
        $model->setAttr('pay_origin',$pay_origin);
        $model->setAttr('pay_info',$data);
        if($pay_way=='paypal'){
            if(isset($data['resource_type']) && isset($data['event_type']) && $data['resource_type']=='checkout-order' && $data['event_type']=='CHECKOUT.ORDER.APPROVED'){
                $purchase_units = $data['resource']['purchase_units']??[];
            }else{
                $purchase_units =$data['purchase_units']??[];
            }
            $purchase_units_first = $purchase_units[0]??[];
            if(isset($purchase_units_first['payments'])){
                $captures = $purchase_units_first['payments']['captures'];
                $captures_first = $captures[0]??[];
                if(!empty($captures_first)){
                    $model->setAttr('paypal_capture_id',$captures_first['id']);
                }
            }
//            dump($purchase_units,$captures_first,$model->getAttr('paypal_capture_id'));exit;
        }

        return $model->_sure_pay($pay_way);
    }


}